package org.apache.james.imap.server;

import java.net.InetSocketAddress;
import java.net.SocketAddress;

import org.apache.james.imapserver.ImapHandlerInterface;
import org.apache.james.imapserver.ImapResponse;
import org.apache.james.imapserver.ImapSessionImpl;
import org.apache.james.mailboxmanager.manager.MailboxManagerProvider;
import org.apache.james.services.UsersRepository;
import org.apache.mina.common.IoSession;

public class MinaImapSession extends ImapSessionImpl implements
		ImapHandlerInterface {
	public final static String KEY = MinaImapSession.class.getName();

	IoSession ioSession;

	SimpleImapResponse responseFormatter;

	public MinaImapSession(IoSession ioSession,
			MailboxManagerProvider mailboxManagerProvider, UsersRepository users) {
		super(mailboxManagerProvider, users);
		this.ioSession = ioSession;
		setHandler(this);
		SocketAddress remoteAddress = this.ioSession.getRemoteAddress();
		if (remoteAddress instanceof InetSocketAddress) {
			InetSocketAddress inetSocketAddress = (InetSocketAddress) remoteAddress;
			setClientHostName(inetSocketAddress.getHostName());
			setClientAddress(inetSocketAddress.getAddress().getHostAddress());
		}
		this.responseFormatter = new SimpleImapResponse(ioSession);
		this.ioSession.setAttribute(MinaImapSession.KEY, this);
	}

	public static MinaImapSession get(IoSession ioSession) {
		return (MinaImapSession) ioSession.getAttribute(MinaImapSession.KEY);
	}
	
	
	public ImapResponse getImapResponseFormatter() {
		return responseFormatter;
	}

	@Override
	public String getClientHostname() {
		SocketAddress remoteAddress = this.ioSession.getRemoteAddress();
		if (remoteAddress instanceof InetSocketAddress) {
			return ((InetSocketAddress) remoteAddress).getHostName();
		}
		return "unknown";
	}

	@Override
	public String getClientIP() {
		SocketAddress remoteAddress = this.ioSession.getRemoteAddress();
		if (remoteAddress instanceof InetSocketAddress) {
			return ((InetSocketAddress) remoteAddress).getAddress()
					.getHostAddress();
		}
		return "";
	}

	public void forceConnectionClose(String byeMessage) {

		responseFormatter.byeResponse(byeMessage);
		ioSession.close();
	}

	public void resetHandler() {
		ioSession.close();
	}

}
